package com.zhx.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @program: web-framework
 * @author: zhx
 * @create: 2021-03-20 21:55
 **/
public class ExitFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //点击退出按钮的时候会触发
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/web_framework/exit")){
            //删除session
            request.getSession(false).removeAttribute("user");
            // request.getSession(false).invalidate(); //这个方法执行会触发session监听器的销毁
            //不能调用上面的方法，因为此刻，我只是退出了，变为了普通游客
            String id = request.getSession().getId();
            System.out.println("退出id："+id);
            ServletContext application = request.getServletContext();
            Map<String,String> online = (Map<String, String>) application.getAttribute("online");
            if (online !=null){
                online.put(id, "游客");
            }
            application.setAttribute("online",online );
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/Login.jsp");
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
